package com.woniuxy.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.woniuxy.dao.CoachDao;
import com.woniuxy.dao.FocusDao;
import com.woniuxy.dao.GymCoachDao;
import com.woniuxy.dao.MessageDao;
import com.woniuxy.dao.OrdersDao;
import com.woniuxy.entity.ChooseCourse;
import com.woniuxy.entity.CoachInfo;
import com.woniuxy.entity.Course;
import com.woniuxy.entity.GymCoach;
import com.woniuxy.entity.Message;
import com.woniuxy.entity.Orders;
import com.woniuxy.entity.PageBean;
import com.woniuxy.entity.User;
import com.woniuxy.service.CoachService;
import com.woniuxy.util.CommonUtil;
/**
 * 
 * @author lishuwei
 *
 */
@Service
public class CoachSerciveImpl implements CoachService {
	@Autowired
	private OrdersDao ordersDao;
	@Autowired
	private CoachDao coachDao;
	@Autowired
	private MessageDao messageDao;
	@Autowired
	private GymCoachDao gymCoachDao;
	@Autowired
	private FocusDao focusDao;

	@Override
	public List<User> getNearbyUsers(User user, double distance, String role) {

		double r = 6371.393; // 地球半径千米
		double latitude = user.getLatitude();
		double longitude = user.getLongitude();
		double dlng = 2 * Math.asin(Math.sin(distance / (2 * r)) / Math.cos(latitude * Math.PI / 180));// 角度差计算
		dlng = dlng * 180 / Math.PI;
		double dlat = distance / r;// 角度差计算
		dlat = dlat * 180 / Math.PI;// 转化为纬度度差
		double latitudeMin = latitude - dlat;
		double latitudeMax = latitude + dlat;
		double longitudeMin = longitude - dlng;
		double longitudeMax = longitude + dlng;
		// 找出方格内的所有用户再进行进一步排除及排序
		List<User> users = coachDao.getUsersByLatitudeAndLongitude(latitudeMax, latitudeMin, longitudeMax,
				longitudeMin);
		List<User> nearUsers = new ArrayList<User>();
		for (User nearUser : users) {
			double radLatMain = latitude * Math.PI / 180.00;
			double radLatSub = nearUser.getLatitude() * Math.PI / 180.00;
			double dradlat = radLatMain - radLatSub;
			double dradlng = (longitude - nearUser.getLongitude()) * Math.PI / 180.00;
			double drad = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(dradlat / 2), 2)
					+ Math.cos(radLatMain) * Math.cos(radLatSub) * Math.pow(Math.sin(dradlng / 2), 2)));
			double dis = Math.round(drad * r);
			if (dis < distance && role.equals(nearUser.getRole())) {
				nearUsers.add(nearUser.setDistance(dis));
			}
		}

		return nearUsers;
	}

	@Override
	public User getUserById(long id) {
		User user = coachDao.getUserById(id);
		//针对信息联系方式是否可见做处理
		user = CommonUtil.setInfoByRank(user, focusDao);
		return user;

	}

	@Override
	public int sendMessage(Message message) {
		if (message.getOrderId() != 0) {
			return messageDao.addOrderMessage(message);
		} else if (message.getSginId() != 0) {
			return messageDao.addSignMessage(message);
		}
		return messageDao.addMessage(message);
	}

	@Override
	public CoachInfo getCoachInfoById(long id) {

		return coachDao.getCoachInfoById(id);
	}

	@Override
	@Transactional
	public int addOrder(Orders order) {
		
		if (order.getUserIdGym()!=0) {
			return ordersDao.addGymOrder(order);
		}
		System.out.println(order.getId());
		
		return ordersDao.addOrder(order);
	}

	@Override
	@Transactional
	public int addSgin(GymCoach gymCoach, String info,String role) {
		coachDao.addGymCoach(gymCoach);
		Message message = new Message();
		if ("2".equals(role)) {
			message.setContent(
					coachDao.getUserById(gymCoach.getUserIdCoach()).getNickname() + "：我向您发起了签约申请，快将我收入麾下吧！！！ " + info)
					.setMessageStatus("2").setUserIdAccepter(gymCoach.getUserIdGym())
					.setUserIdSender(gymCoach.getUserIdCoach()).setSginId(gymCoach.getId());
			messageDao.addSignMessage(message);
		}else if ("3".equals(role)) {
			message.setContent(
					coachDao.getUserById(gymCoach.getUserIdGym()).getNickname() + "：我向您抛出了橄榄枝，愿少侠鼎力相助！！！ " + info)
					.setMessageStatus("2").setUserIdAccepter(gymCoach.getUserIdCoach())
					.setUserIdSender(gymCoach.getUserIdGym()).setSginId(gymCoach.getId());
			messageDao.addSignMessage(message);
		}
		
		return 1 ;
	}

	@Override
	public PageBean<User> getFriendsByPage(long id, Integer page) {
		PageBean<User> pageBean = new PageBean<User>();
		int pagesize = 5;
		int totalNum = coachDao.getStudentsNum(id);
		List<User> students = coachDao.getStudentsByPage(id, (page - 1) * pagesize, pagesize);
		if (students == null || students.size() == 0) {
			return pageBean;
		}
		pageBean.setList(students);
		pageBean.setNowNum(students.size());
		pageBean.setPageSize(pagesize);
		pageBean.setTotalNum(totalNum);
		pageBean.setTotalPage(totalNum % pagesize == 0 ? totalNum / pagesize : totalNum / pagesize + 1);
		pageBean.setNowPage(page);
		return pageBean;
	}

	@Override
	public int getGymCoachByCIdAndGid(long cid, long gid) {
		// TODO Auto-generated method stub
		return gymCoachDao.getGymCoachByCIdAndGid(cid, gid);
	}

	@Override
	public void sendOrderMessage(Message message) {
		messageDao.addOrderMessage(message);

	}

	@Override
	public PageBean<GymCoach> getSginsByPage(long id, int page) {
		PageBean<GymCoach> pegeBean = new PageBean<>();
		int pagesize = 5;
		int totalNum = coachDao.getSignsNum(id);
		List<GymCoach> signs = coachDao.getSignsByPage(id, (page - 1) * pagesize, pagesize);

		if (signs == null || signs.size() == 0) {
			return pegeBean;
		}
		pegeBean.setList(signs);
		pegeBean.setNowNum(signs.size());
		pegeBean.setPageSize(pagesize);
		pegeBean.setTotalNum(totalNum);
		pegeBean.setTotalPage(totalNum % pagesize == 0 ? totalNum / pagesize : totalNum / pagesize + 1);
		pegeBean.setNowPage(page);
		return pegeBean;
	}

	@Override
	@Transactional
	public void updateSignStatus(GymCoach gymCoach, String status,String role) {
		Message message = new Message();
		String content = "";
		if ("2".equals(role)) {
			message.setMessageStatus("2").setUserIdAccepter(gymCoach.getUserIdGym())
			.setUserIdSender(gymCoach.getUserIdCoach());
			content = coachDao.getUserById(gymCoach.getUserIdCoach()).getNickname() ;
		}else if("3".equals(role)) {
			message.setMessageStatus("2").setUserIdSender(gymCoach.getUserIdGym())
			.setUserIdAccepter(gymCoach.getUserIdCoach());
			content = coachDao.getUserById(gymCoach.getUserIdGym()).getNickname() ;
		}
		if ("3".equals(status)) {
			content = content + "：我接受了您的签约申请，喜提一员猛将！";
			message.setContent(content);
			coachDao.updateSignStatus(gymCoach.getId(), status);
		} else if ("4".equals(status)) {
			content = content + "：我拒绝了您的签约申请，来日方长嘛！";
			message.setContent(content);
			coachDao.updateSignStatus(gymCoach.getId(), status);
		}
	
		
		System.out.println(message);
		messageDao.addMessage(message);
		

	}

	@Override
	public void updateUser(User user) {
		// TODO Auto-generated method stub
		System.out.println("user:" + user);
		try {
			coachDao.updateUserBaseInfo(user);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}


	@Override
	@Transactional
	public void updateCoach(User user) {
		coachDao.updateUserBaseInfo(user);
		coachDao.updateExtraInfo(user.getCoachInfo());
		
	
	}

	@Override
	public PageBean<User> getSginCoachesByPage(Integer id, Integer page) {
		PageBean<User> pegeBean = new PageBean<>();
		int pagesize = 5;
	
		long gid =id;
		int totalNum = coachDao.getSignsCoachesNum(gid);
		List<User> coaches = coachDao.getSignsCoachesByPage(gid, (page - 1) * pagesize, pagesize);

		if (coaches == null || coaches.size() == 0) {
			return pegeBean;
		}
		pegeBean.setList(coaches);
		pegeBean.setNowNum(coaches.size());
		pegeBean.setPageSize(pagesize);
		pegeBean.setTotalNum(totalNum);
		pegeBean.setTotalPage(totalNum % pagesize == 0 ? totalNum / pagesize : totalNum / pagesize + 1);
		pegeBean.setNowPage(page);
		return pegeBean;
	}

	@Override
	public Course getCourseById(long courseId) {
		// TODO Auto-generated method stub
		return coachDao.getCourseById(courseId);
	}

	@Override
	public ChooseCourse getChooseCourseById(long chooseId) {
		// TODO Auto-generated method stub
		return coachDao.getChooseCourseById(chooseId);
	}

	

	

}

